<template>
  <view>
    <u-popup
        :show="show"
        position="bottom"
        :closeOnClickOverlay="true"
        bg-color="rgba(0,0,0,0)"
        @close="close">
      <view class="box">
        <view class="goods-info">
          <view class="goods-img"
                v-if="goods.bodyJson && goods.bodyJson.length > 0">
            <image
                mode="aspectFill"
                class="goods-image"
                :src="$kt.file.visit(goods.bodyJson[0].value)"></image>
          </view>
          <view class="goods-text">
            <!--              <view class="goods-name">{{goods.name}}</view>-->
            <view
                v-if="requestParam.number"
                class="goods-price">
              <view class="goods-price-dot">￥</view>
              <!-- {{ goods.price }} -->
              {{ $kt.math.evaluate(goods.price + "*" + requestParam.number) }}
              <view
                  class="goods-stock"
              v-if="!goods.stockNumber"
              >{{$i18n.zhToGlobal('已售罄')}}</view>
              <view
                  class="goods-stock"
                  v-else>
                {{ $i18n.zhToGlobal('剩余') }}：{{ goods.stockNumber }}
              </view>
            </view>
            <view class="goods-ii">
              <view>
                <view
                    @click="addRequestNumber(-1)"
                    class="goods-price-dot-in goods-price-dot-in-left">-
                </view>
                <view class="goods-price-input-input">
                  <input type="number"
                         @input="requestParamNumberInput"
                         style="border: none"
                         v-model="requestParam.number" class="goods-price-input"></input>
                </view>
                <view
                    @click="addRequestNumber(1)"
                    class="goods-price-dot-in goods-price-dot-in-right">+
                </view>
              </view>
            </view>
          </view>
        </view>
        <view style="padding: 0 20px 20rpx 20rpx;box-sizing: border-box">
          <scroll-view
              style="max-height: 500rpx;min-height: 200px"
              scroll-y>
            <view
              v-if="goods.isHasAttr">

            <view
                class="attr-box"
                v-if="shop.getAttrI18nByGoodsAttrId(item.attrId).name&&(index===0||hasAttrSelected(item.attrId))"
                v-for="(item,index) in goods.attrs">
              <view
                  class="title"
              >{{ $kt.util.firstLetterUpper(shop.getAttrI18nByGoodsAttrId(item.attrId).name) }}
              </view>
              <view>
                <view
                    v-for="(attr, index1) in attrMap[item.attrId]"
                    @click="selectAttr(attr.attrId, attr.value)"
                    v-if="index===0||hasAttrValue(item.attrId, attr.value)"
                    class="tag"
                    :class="{
                      'tag-selected': isAttrSelected(item.attrId, attr.value),
                    }"
                    style="margin-top: 10rpx">
                  <!-- {{ attr.value }} -->
                  {{getByTextId(attr.textId,attr.value)}}
                </view>
              </view>
            </view>

            </view>
          </scroll-view>
        </view>
        <view style="height: 30rpx"></view>
        <view>
          <slot
         :param="requestParam"
          ></slot>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import shop from "@/js/shop";

export default {
  data() {
    return {
      shop,
      show: false,
      goods: {},
      requestParam: {
        goodsId: '',
        number: 1,
        attrs:[],
        attrGroupId: 0
      },
      attrMap: {},
      textMap: {}
    };
  },
  // 监听数据变化
  watch: {
    goods: {
      handler: function (val, oldVal) {
        this.initAttrMap();
        this.getViewListByGoodsId(val.id);
      },
      deep: true
    },
    // // 监听requestParam.number的变化
    // 'requestParam.number': {
    //   handler: function (val, oldVal) {
    //     // 如果数量小于1，设置为1
    //     if (this.requestParam.number < 1) {
    //       this.requestParam.number = 1;
    //     }
    //     // 如果数量大于库存，设置为库存
    //     if (this.requestParam.number > this.goods.stockNumber) {
    //       this.requestParam.number = this.goods.stockNumber;
    //     }
    //     // 如果有小数点，设置为整数
    //     if ((this.requestParam.number + "").indexOf('.') !== -1) {
    //       this.requestParam.number = parseInt((this.requestParam.number + "").split('.')[0]);
    //     }
    //   },
    // },
  },
  mounted() {

  },
  methods: {
    // 是否可以进行下一步
    isCanNext() {
      if(!this.isSelectAttr(this.requestParam)){
        return false;
      }
      if(!this.goods.stockNumber){
        return false;
      }
    },

    // 输入数量
    getViewListByGoodsId(goodsId){
      this.$kt.request.send({
        uri: '/business-shop-web/shopGoodsTextI8n/getViewListByGoodsId',
        data: {
          goodsId
        },
        stateSuccess: (res) => {
          console.log(res.data,"-=-=")
          this.textMap = {};
          for (let i = 0; i < res.data.length; i++) {
            this.textMap[res.data[i].id] = res.data[i].text;
          }
        }
      });
    },
    getByTextId(textId,text){
      try{
        return this.textMap[textId] || text;
      }catch (e) {
        return text;
      }
    },

    requestParamNumberInput(e) {
      this.requestParam.number = e.target.value;
      // 如果数量小于1，设置为1
      if (this.requestParam.number < 1) {
        this.requestParam.number = 1;
      }
      // 如果数量大于库存，设置为库存
      if (this.requestParam.number > this.goods.stockNumber) {
        this.requestParam.number = this.goods.stockNumber;
      }
      // 如果有小数点，设置为整数
      if ((this.requestParam.number + "").indexOf('.') !== -1) {
        this.requestParam.number = parseInt((this.requestParam.number + "").split('.')[0]);
      }
      this.$forceUpdate();
    },
    addRequestNumber(num) {
      this.requestParam.number = parseInt(this.requestParam.number) + parseInt(num);
      console.log(this.requestParam.number);
      // 如果数量小于1，设置为1
      if (this.requestParam.number < 1) {
        this.requestParam.number = 1;
      }
      // 如果数量大于库存，设置为库存
      if (this.requestParam.number > this.goods.stockNumber) {
        this.requestParam.number = this.goods.stockNumber;
      }
      // 如果有小数点，设置为整数
      if ((this.requestParam.number + "").indexOf('.') !== -1) {
        this.requestParam.number = parseInt((this.requestParam.number + "").split('.')[0]);
      }
      this.$forceUpdate();
    },
    // 是否选择好了属性
    isSelectAttr(requestParam) {
      if (this.goods.isHasAttr) {
        for (let i = 0; i < this.goods.attrs.length; i++) {
          let has = false;
          for (let j = 0; j < this.requestParam.attrs.length; j++) {
            if (this.goods.attrs[i].attrId === this.requestParam.attrs[j].attrId) {
              has = true;
              break;
            }
          }
          if (!has) {
            return false;
          }
        }
      }
      return true;
    },

    initAttrMap(){
      if (this.goods.attrGroups) {
        // this.goods.attrGroups 示例
        // [{"attrs":[{"attrGroupId":592950479011845,"attrId":1,"id":592950481707013,"value":"中国"},{"attrGroupId":592950479011845,"attrId":2,"id":592950483795973,"value":"红色"}],"goodsId":592878754738181,"id":592950479011845,"price":"1","stockNumber":0},{"attrs":[{"attrGroupId":592950486671365,"attrId":1,"id":592950489391109,"value":"美国"},{"attrGroupId":592950486671365,"attrId":2,"id":592950491451397,"value":"蓝色"}],"goodsId":592878754738181,"id":592950486671365,"price":"","stockNumber":0},{"attrs":[{"attrGroupId":592950494306309,"attrId":1,"id":592950497026053,"value":"中国"},{"attrGroupId":592950494306309,"attrId":2,"id":592950499086341,"value":"绿色"}],"goodsId":592878754738181,"id":592950494306309,"price":"","stockNumber":0}]
        // 将attrGroups转换为attrMap，方便查找
        this.attrMap = {};
        for (let i = 0; i < this.goods.attrGroups.length; i++) {
          let attrGroup = this.goods.attrGroups[i];
          for (let j = 0; j < attrGroup.attrs.length; j++) {
            let attr = attrGroup.attrs[j];
            if (!this.attrMap[attr.attrId]) {
              this.attrMap[attr.attrId] = [];
            }
            // 查询是否有相同的value，如果有，不添加
            let has = false;
            for (let k = 0; k < this.attrMap[attr.attrId].length; k++) {
              if (this.attrMap[attr.attrId][k].value === attr.value) {
                has = true;
                break;
              }
            }
            if (!has) {
              this.attrMap[attr.attrId].push(attr);
            }
          }
        }
        console.log(JSON.stringify(this.attrMap));
      }
    },
    selectAttr(attrId, value) {
      console.log(attrId,value);
      // 如果attrId在第一个将所有的attrId清空
      if (this.goods.isHasAttr) {
        if (this.goods.attrs[0].attrId === attrId) {
          this.requestParam.attrs = [];
        }
        if(this.goods.attrs[1].attrId === attrId){

            for (let i = 0; i < this.requestParam.attrs.length; i++) {
              if (this.requestParam.attrs[i].attrId !== this.goods.attrs[0].attrId) {
                this.requestParam.attrs.splice(i, 1);
                break;
              }
            }

        }
      }


      let has = false;
      for (let i = 0; i < this.requestParam.attrs.length; i++) {
        if (this.requestParam.attrs[i].attrId === attrId) {
          this.requestParam.attrs[i].value = value;
          has = true;
          break;
        }
      }
      if (!has) {
        this.requestParam.attrs.push({
          attrId: attrId,
          value: value
        });
      }

      // 如果选择完了属性，获取价格和库存
      if (this.isSelectAttr(this.requestParam)) {
        // 对应的attrGroup中有库存和单价
        for (let i = 0; i < this.goods.attrGroups.length; i++) {
          let attrGroup = this.goods.attrGroups[i];
          let has = true;
          for (let j = 0; j < this.requestParam.attrs.length; j++) {
            let hasAttr = false;
            for (let k = 0; k < attrGroup.attrs.length; k++) {
              if (this.requestParam.attrs[j].attrId === attrGroup.attrs[k].attrId && this.requestParam.attrs[j].value === attrGroup.attrs[k].value) {
                hasAttr = true;
                break;
              }
            }
            if (!hasAttr) {
              has = false;
              break;
            }
          }
          if (has) {
            this.goods.price = attrGroup.price;
            this.goods.stockNumber = attrGroup.stockNumber;
            break;
          }
        }
      }


      // 根据所有的选择的属性找到对应的attrGroup
      let attrGroupId = null;
      for (let i = 0; i < this.goods.attrGroups.length; i++) {
        let attrGroup = this.goods.attrGroups[i];
        let has = true;
        for (let j = 0; j < this.requestParam.attrs.length; j++) {
          let hasAttr = false;
          for (let k = 0; k < attrGroup.attrs.length; k++) {
            if (this.requestParam.attrs[j].attrId === attrGroup.attrs[k].attrId && this.requestParam.attrs[j].value === attrGroup.attrs[k].value) {
              hasAttr = true;
              break;
            }
          }
          if (!hasAttr) {
            has = false;
            break;
          }
        }
        if (has) {
          attrGroupId = attrGroup.id;
          break;
        }
      }
      this.requestParam.attrGroupId = attrGroupId;

    },
    open(goods) {
      this.show = true;
      this.goods = JSON.parse(JSON.stringify(goods));
      this.requestParam.goodsId = goods.id;
      console.log(JSON.stringify(goods.attrGroups));
    },
    close() {
      this.show = false;
    },
    // 查询各自都有的属性值，根据requestParam.attrs
    hasAttrValue(attrId, value) {
      // 比如中国可以选红色和绿色，那么蓝色不在可选范围内，attrId和value的形参是从列表中获取的
      // 遍历所有的attrGroups，如果有一个attrGroup的attrs包含了所有的requestParam.attrs，那么就返回true，否则返回false

      let requestParam = JSON.parse(JSON.stringify(this.requestParam));
      // 如果是相同的attrId，则删除
      for (let i = 0; i < requestParam.attrs.length; i++) {
        if (requestParam.attrs[i].attrId === attrId) {
          requestParam.attrs.splice(i, 1);
          break;
        }
      }

      for (let i = 0; i < this.goods.attrGroups.length; i++) {
        let attrGroup = this.goods.attrGroups[i];
        let has = true;
        for (let j = 0; j < requestParam.attrs.length; j++) {
          let hasAttr = false;
          for (let k = 0; k < attrGroup.attrs.length; k++) {
            if (requestParam.attrs[j].attrId === attrGroup.attrs[k].attrId && requestParam.attrs[j].value === attrGroup.attrs[k].value) {
              hasAttr = true;
              break;
            }
          }
          if (!hasAttr) {
            has = false;
            break;
          }
        }
        if (has) {
          // 如果有一个attrGroup的attrs包含了所有的requestParam.attrs，那么就返回true
          for (let j = 0; j < attrGroup.attrs.length; j++) {
            if (attrGroup.attrs[j].attrId === attrId && attrGroup.attrs[j].value === value) {
              return true;
            }
          }
        }
      }


      return false;
    },

    isAttrSelected(attrId, value) {
      for (let i = 0; i < this.requestParam.attrs.length; i++) {
        if (this.requestParam.attrs[i].attrId === attrId && this.requestParam.attrs[i].value === value) {
          return true;
        }
      }
      return false;
    },
    // 查看是否有一个满足，根据hasAttrValue
    hasAttrSelected(attrId) {
      for (let i = 0; i < this.attrMap[attrId].length; i++) {
        if (this.hasAttrValue(attrId, this.attrMap[attrId][i].value)) {
          return true;
        }
      }
      return false;
    }

  }
}
</script>

<style lang="scss">
.box {
  width: 100%;
  background-color: #fff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 999;
}

.goods-info {
  padding: 20px;
  box-sizing: border-box;

  .goods-img {
    display: inline-block;
    width: 150rpx;
    height: 150rpx;

    .goods-image {
      width: 100%;
      height: 100%;
    }
  }

  .goods-text {
    display: inline-block;
    width: calc(100% - 150rpx);
    padding-left: 20rpx;
    box-sizing: border-box;
    vertical-align: top;

    .goods-price-dot {
      display: inline-block;
      font-size: 40rpx;
      color: #FF0000;
    }

    .goods-price {
      font-size: 50rpx;
      color: #FF0000;
      font-weight: bold;
    }

    .goods-name {
      font-size: 32rpx;
      color: #333;
      // 超出两行不显示，用省略号代替
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
  }

}

.goods-ii {
  position: relative;
  display: inline-block;
  padding: 20rpx 70rpx 20rpx 70rpx;

  .goods-price-dot-in {
    display: inline-block;
    font-size: 40rpx;
    color: #666666;
    font-weight: bold;
    width: 60rpx;
    height: 60rpx;
    text-align: center;
    border-radius: 10px;
    background-color: #F0F0F0;
  }

  .goods-price-dot-in-left {
    position: absolute;
    left: 0;
  }

  .goods-price-dot-in-right {
    position: absolute;
    right: 0;
  }

  .goods-price-input-input {
    display: inline-block;
    width: 200rpx;
    height: 60rpx;
    border: 1rpx solid #F0F0F0;
    border-radius: 10rpx;

    .goods-price-input {
      width: 100%;
      height: 100%;
      text-align: center;
      font-size: 30rpx;
      color: #333;
      border: none;
    }
  }
}

.goods-price-dot-in:active {
  opacity: .9;
}

.attr-box {
  padding: 20rpx;
  box-sizing: border-box;

  .title {
    font-size: 30rpx;
    color: #333;
    font-weight: bold;
  }
}

.tag {
  display: inline-block;
  padding: 10rpx 20rpx;
  border: 1rpx solid #F0F0F0;
  border-radius: 20rpx;
  margin-right: 20rpx;
  margin-top: 20rpx;
  font-size: 30rpx;
  color: #666666;
}

.tag-selected {
  background-color: #000000;
  color: #FFFFFF;
}

.goods-stock{
  display: inline-block;
  font-size: 28rpx;
  color: #999999;
  margin-left: 20rpx;
  font-weight: normal;
}
</style>
